package cn.bluethink.eguan.rewardtask.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.bluethink.eguan.core.security.Token;
import cn.bluethink.eguan.core.service.EgUserService;
import cn.bluethink.eguan.model.core.EgPurview;
import cn.bluethink.eguan.model.core.EgRole;
import cn.bluethink.eguan.model.core.EgTaskStatus;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.model.rewardtask.EgRewardTask;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.result.ResponseMessage;
import cn.bluethink.eguan.result.ResponseResult;
import cn.bluethink.eguan.rewardtask.filter.RewardTaskFilter;
import cn.bluethink.eguan.rewardtask.service.EgReceiverService;
import cn.bluethink.eguan.rewardtask.service.EgRewardTaskService;

/**
 * 悬赏任务控制器
 * 
 * @author 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.2.0
 * @brief 驿馆+产品
 * @note 修订历史： 1.wanglei于2018/10/18设计并构建初始版本v0.2.0
 *       2.wanglei于2018/11/15修订悬赏任务打赏时的账户处理
 */
@CrossOrigin
@RestController
@RequestMapping("/eguan/v1.0/rewardtask")
public class EgRewardTaskController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private EgUserService userService;

    @Autowired
    private EgRewardTaskService rewardTaskService;

    @Autowired
    private EgReceiverService receiverService;

    /**
     * 发布个人或团队悬赏任务。 包括：任务标题，任务详情，参与类型(无限制/固定人数)，截止日期，金币奖励
     * 
     * @param rewardtask
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.PERSONAL_REWARD_TASK, EgPurview.TEAM_REWARD_TASK })
    @PostMapping("/create")
    public ResponseResult<EgRewardTask> create(@RequestBody EgRewardTask rewardTask) throws Exception {
        // String token = request.getHeader("Authorization");
        Long uid = (Long) request.getAttribute("userId");
        // 获取用户的基本信息(包括位置对象ID，账户ID)
        EgUser user = userService.getUser(uid, false);
        if (user == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        }
        // 获取用户位置对象类型ID，位置对象ID，以及个人悬赏逻辑标识,默认是团队悬赏
        Integer otype = user.getPos().getType().getOtid();
        Long oid = user.getPos().getId();
        Boolean bmine = rewardTask.getBmine() == null ? false : rewardTask.getBmine();
        // 获取引用的账户ID
        Long acount = rewardTaskService.getAcountByTaskType(oid, otype, bmine, user);
        if (acount == 0L) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND.getStatus(), "引用的账户不存在！");
        }
        // 创建悬赏任务
        EgRewardTask result = rewardTaskService.create(rewardTask, user, acount);
        if (result != null) {
            return new ResponseResult<>(ResponseMessage.OK, result);
        }
        return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
    }

    /**
     * 删除悬赏任务。 1.有审核权限的用户直接删除； 2.谁创建的悬赏任务谁删除； 3.对于发布者而言,无人揭榜的悬赏任务，允许删除；
     * 4.新修订：悬赏结束后，允许发布者进行删除操作。
     * 
     * @param tid
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.OBJECT_CHECK, EgPurview.PERSONAL_REWARD_TASK, EgPurview.TEAM_REWARD_TASK })
    @PostMapping("/del")
    public ResponseResult<Long> del(@RequestParam Long tid) throws Exception {
        // String token = request.getHeader("Authorization");
        Long uid = (Long) request.getAttribute("userId");
        // 获取该悬赏任务详情
        EgRewardTask rewardTask = rewardTaskService.detail(tid);
        if (rewardTask == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        }
        // 根据当前登录用户ID获取当前登录用户权限,判断当前用户是否拥有审核权限，有则可以直接删除
        EgRole role = userService.mypurview(uid);
        if (role != null && (role.getPurview() & EgPurview.OBJECT_CHECK) > 0) {
            if (!rewardTaskService.del(tid)) {
                return new ResponseResult<>(ResponseMessage.DELETE_FAIL);
            }
            return new ResponseResult<>(ResponseMessage.OK, tid);
        }
        // 判断当前登录用户是否是任务创建者
        if (!uid.equals(rewardTask.getCuser().getId())) {
            return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
        }
        // 如果该任务已揭榜，即领取者状态是进行中,不能删除;但任务已结束发布者可以删除
        if (!rewardTask.getStatus().equals(EgTaskStatus.STATUS_FINISH)
                && receiverService.getReceiversCount(tid, EgTaskStatus.STATUS_HANDLE) > 0) {
            return new ResponseResult<>(ResponseMessage.UNDELETE);
        }
        // 删除操作
        if (rewardTaskService.del(tid)) {
            return new ResponseResult<>(ResponseMessage.OK, tid);
        }
        return new ResponseResult<>(ResponseMessage.DELETE_FAIL);
    }

    /**
     * 更新悬赏任务信息。 1.更新任务的基本信息； 2.更新任务的状态：开始(进行中)、结束(完成))； 3.对于发布者而言，悬赏任务点击开始后，不允许修改。
     * 
     * @param rewardtask
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.PERSONAL_REWARD_TASK, EgPurview.TEAM_REWARD_TASK })
    @PostMapping("/update")
    public ResponseResult<EgRewardTask> update(@RequestBody EgRewardTask rewardTask) throws Exception {
        // String token = request.getHeader("Authorization");
        Long uid = (Long) request.getAttribute("userId");
        if (rewardTask.getId() == null || rewardTask.getId() == 0) {
            return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
        }
        // 获取用户的基本信息(包括位置对象)
        EgUser user = userService.getUser(uid, false);
        if (user == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        }
        // 获取该悬赏任务的详情
        EgRewardTask oldTask = rewardTaskService.detail(rewardTask.getId());
        if (oldTask == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        }
        // 判断当前登录用户是否是任务创建者
        if (!uid.equals(oldTask.getCuser().getId())) {
            return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
        }
        // 获取该悬赏任务的原状态以及待更新状态
        Integer oldStatus = oldTask.getStatus();
        Integer upStatus = rewardTask.getStatus();
        // 若更新的状态已存在，直接返回
        if (upStatus != null && oldStatus.equals(upStatus)) {
            return new ResponseResult<>(ResponseMessage.OK, oldTask);
        }
        // 如果原状态是未开始，发布者可以编辑基本信息
        if (oldStatus.equals(EgTaskStatus.STATUS_NEW)) {
            // 如果是更新任务类型（比较特殊需要更新账户）
            Boolean upBmine = rewardTask.getBmine();
            if (upBmine != null && !upBmine.equals(oldTask.getBmine())) {
                // 获取悬赏任务的发布位置信息
                Long oid = oldTask.getPos().getId();
                Integer otype = oldTask.getPos().getType().getOtid();
                // 获取该任务引用的账户ID
                Long acount = rewardTaskService.getAcountByTaskType(oid, otype, upBmine, user);
                if (acount != 0L) {
                    oldTask.setBmine(upBmine);
                    if (rewardTaskService.update(oldTask, acount) == null) {
                        return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
                    }
                    return new ResponseResult<>(ResponseMessage.OK, oldTask);
                }
            }
            oldTask = rewardTaskService.updateProperty(oldTask, rewardTask, user);
        }
        // 如果将原状态更新为【进行中】，设置开始时间
        if (upStatus != null && upStatus.equals(EgTaskStatus.STATUS_HANDLE)) {
            oldTask.setStatus(EgTaskStatus.STATUS_HANDLE);
            oldTask.setBtime(new Date());
        }
        // 如果将原状态更新为【完成】，设置完成时间
        if (upStatus != null && upStatus.equals(EgTaskStatus.STATUS_FINISH)) {
            oldTask.setStatus(EgTaskStatus.STATUS_FINISH);
            oldTask.setFtime(new Date());
        }
        // 更新操作
        EgRewardTask result = rewardTaskService.update(oldTask, null);
        if (result != null) {
            return new ResponseResult<>(ResponseMessage.OK, result);
        }
        return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
    }

    /**
     * 获取悬赏任务详情。
     * 
     * @param tid
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.PERSONAL_REWARD_TASK, EgPurview.TEAM_REWARD_TASK })
    @GetMapping("/detail")
    public ResponseResult<EgRewardTask> detail(@RequestParam Long tid) throws Exception {
        EgRewardTask rewardTask = rewardTaskService.detail(tid);
        if (rewardTask != null) {
            return new ResponseResult<>(ResponseMessage.OK, rewardTask);
        }
        return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
    }

    /**
     * 根据过滤条件查询悬赏任务列表。
     * 1.根据发布者Id查询，默认待打赏的(完成的)在最前面，其余按照创建时间降序排序；根据任务状态筛选后，按照创建时间降序排序；
     * 2.根据任务发布位置对象ID查询，只查询进行中的并且没有过期的任务，按照创建时间降序排序。
     * 
     * @param filter
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.PERSONAL_REWARD_TASK, EgPurview.TEAM_REWARD_TASK })
    @PostMapping("/query")
    public ResponseResult<PageInfo<EgRewardTask>> query(@RequestBody RewardTaskFilter filter) throws Exception {
        return new ResponseResult<>(ResponseMessage.OK, rewardTaskService.query(filter));
    }

}
